package cn.sunshine;

import lombok.SneakyThrows;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;

/**
 * @Description 自定义网络类加载器
 * @Author Mokairui
 * @Since 2021/12/4
 */
public class MyURLClassLoader extends ClassLoader {
    private String url;

    public MyURLClassLoader(String url) { // 从父类假爱是系统类加载器 appLoader
        this.url = url;
    }

    @SneakyThrows
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String path = url + "/" + name.replace(".", "/") + ".class";
        URL url = new URL(path);
        try (InputStream in = url.openStream();
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = in.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            byte[] data = baos.toByteArray();
            return defineClass(name, data, 0, data.length);
        }
    }

    public static void main(String[] args) throws Exception {
        MyURLClassLoader classLoader = new MyURLClassLoader("http://127.0.0.1:8080/examples");
        Class<?> clazz = classLoader.loadClass("cn.sunshine.Demo");
        clazz.getDeclaredConstructor().newInstance();
    }
}
